<template>
  <view class="w-full min-h-screen order-index bg-[#f0f0f0]">
    <!-- 顶部背景图 -->
    <view class="relative w-full h-[600rpx]">
      <image
        :src="topImage"
        mode="aspectFill"
        class="w-full h-full"
      />
      <view class="absolute inset-0 flex flex-col justify-center items-center bg-black bg-opacity-30">
        <text class="text-white text-[40rpx] font-bold mb-[20rpx]">立即预约</text>
        <text class="text-white text-[32rpx]">师傅免费上门</text>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="w-[680rpx] mx-auto px-[40rpx] py-[24rpx] box-border bg-white rounded-t-[16rpx] shadow-lg mt-[-120rpx] relative z-1">
      <!-- 预约人 -->
      <view class="mb-[40rpx]">
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-800">预约人</text>
          <text class="text-red-500 text-[28rpx] ml-[10rpx]">*</text>
        </view>
        <input
          v-model="form.name"
          type="text"
          placeholder="请填写预约人真实姓名"
          class="w-full px-[24rpx] py-[20rpx] text-[28rpx] placeholder-gray-400 border border-gray-300 rounded-[8rpx] box-border bg-[#eee]"
        />
        <text v-if="errors.name" class="text-red-500 text-[24rpx] mt-[10rpx] block">{{ errors.name }}</text>
      </view>

      <!-- 手机号 -->
      <view class="mb-[40rpx]">
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-800">手机号</text>
          <text class="text-red-500 text-[28rpx] ml-[10rpx]">*</text>
        </view>
        <input
          v-model="form.phone"
          type="number"
          placeholder="请填写预约人手机号"
          class="w-full px-[24rpx] py-[20rpx] text-[28rpx] placeholder-gray-400 border border-gray-300 rounded-[8rpx] box-border bg-[#eee]"
        />
        <text v-if="errors.phone" class="text-red-500 text-[24rpx] mt-[10rpx] block">{{ errors.phone }}</text>
      </view>


      <view class="mb-[40rpx]">
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-800">所在区域</text>
          <text class="text-red-500 text-[28rpx] ml-[10rpx]">*</text>
        </view>
        
        <RegionPicker 
          v-model="form.region"
          :options="options"
          @change="handleRegionChange"
        >
          <view
            type="number"
            placeholder="选择地址"
            class="w-full px-[24rpx] py-[20rpx] min-h-[84rpx] text-[28rpx] placeholder-gray-400 border border-gray-300 rounded-[8rpx] box-border bg-[#eee]"
          >
          {{ regionString || '请选择地址' }}
          </view>
        </RegionPicker>
        <text v-if="errors.region" class="text-red-500 text-[24rpx] mt-[10rpx] block">{{ errors.region }}</text>
      </view>


      <!-- 详细地址 -->
      <view class="mb-[40rpx]">
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-800">详细地址</text>
          <text class="text-red-500 text-[28rpx] ml-[10rpx]">*</text>
        </view>
        <input
          v-model="form.address"
          type="text"
          placeholder="请填写详细地址"
          class="w-full px-[24rpx] py-[20rpx] text-[28rpx] placeholder-gray-400 border border-gray-300 rounded-[8rpx] box-border bg-[#eee]"
        />
        <text v-if="errors.address" class="text-red-500 text-[24rpx] mt-[10rpx] block">{{ errors.address }}</text>
      </view>

      <!-- 备注 -->
      <view class="mb-[40rpx]">
        <text class="block text-[28rpx] text-gray-800 mb-[20rpx]">备注</text>
        <textarea
          v-model="form.remark"
          rows="3"
          type="text"
          placeholder="请填写备注"
          class="w-full px-[24rpx] py-[20rpx] text-[28rpx] border border-gray-300 rounded-[8rpx] box-border bg-[#eee]"
        ></textarea>
      </view>

      <!-- 上传图片 -->
      <view class="mb-[60rpx]">
        <text class="block text-[28rpx] text-gray-800 mb-[20rpx]">上传图片</text>
        <view 
          class="flex items-center flex-col gap-2 justify-center w-full box-border border-2 p-1 border-gray-300 rounded-[8rpx]"
        >
          <image 
            v-if="form.images.length" 
            :src="form.images[0]" 
            mode="widthFix"
            class="w-full"
          />
          <view class="w-full py-4 flex flex-col items-center justify-center" @click="handleUploadImage">
            <text class="text-orange-500 text-[60rpx] leading-none">+</text>
            <text class="text-gray-400 text-[24rpx] py-[10rpx]">点击上传图片</text>
          </view>
        </view>
      </view>

      <nut-button 
        class="!flex mb-[80rpx] mx-auto"
        type="primary"
        @click="handleSubmit"
        :loading="loading"
      >
        立即预约
      </nut-button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import Taro from '@tarojs/taro'
import topImage from '@/assets/imgs/top.png';
import RegionPicker from '@/components/RegionPicker.vue';
import http from '@/utils/http'


// import { showToast } from '@nutui/nutui-taro'
import area from "./data.json";
const showPicker = ref(false)
// const options = ref([])
const options = ref(area);



// 表单数据
const form = reactive({
  name: '',
  phone: '',
  region: ['天津市', '市辖区', '南开区'],
  address: '',
  remark: '',
  images: []
})
const regionString = computed(() => {
  return form.region.length > 0 ? form.region.join(' ') : ''
})

// 错误信息
const errors = reactive({
  name: '',
  phone: '',
  region: '',
  address: ''
})

// 地区选择器相关
const regionCodes = ref([])
const customItem = '全部'

// 加载状态
const loading = ref(false)

// 处理地区选择
const handleRegionChange = (e) => {
  console.log('地区选择:', e)
  form.region = e
  // regionString.value = e.join(' ')
  // regionCodes.value = e.detail.code
  errors.region = ''
}

// 图片上传
const handleUploadImage = async () => {
  // const suc = await checkPermission();
  // console.log("suc", suc)
  // if (!suc) return;
  // try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    
    console.log("选择的图片:", res)

    if (res.tempFilePaths.length > 0) {
      const file = res.tempFilePaths[0]
      form.images = file;
      const t = await http.upload(file);
      console.log("res", t)
      form.images = [t]
    }
  // } catch (error) {
  //   Taro.showToast({
  //     title: '选择图片失败',
  //     icon: 'none'
  //   })
  // }
}

async function checkPermission() {
  try {
    const authRes = await Taro.getSetting()
    if (!authRes.authSetting['scope.writePhotosAlbum']) {
      await Taro.authorize({ scope: 'scope.writePhotosAlbum' })
    }
    if (!authRes.authSetting['scope.camera']) {
      await Taro.authorize({ scope: 'scope.camera' })
    }
    return true
  } catch (err) {
    // 用户拒绝授权时的处理
    Taro.showModal({
      title: '提示',
      content: '需要相册/相机权限才能上传图片',
      showCancel: false
    })
    return false
  }
}

// 表单验证
const validateForm = () => {
  let isValid = true
  
  if (!form.name.trim()) {
    errors.name = '请输入预约人姓名'
    isValid = false
  } else {
    errors.name = ''
  }

  if (!form.phone) {
    errors.phone = '请输入手机号'
    isValid = false
  } else if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    errors.phone = '请输入正确的手机号'
    isValid = false
  } else {
    errors.phone = ''
  }

  if (form.region.length === 0) {
    errors.region = '请选择所在区域'
    isValid = false
  } else {
    errors.region = ''
  }

  if (!form.address.trim()) {
    errors.address = '请输入详细地址'
    isValid = false
  } else {
    errors.address = ''
  }

  return isValid
}

// 获取城市数据
// const getCityData = async () => {
//   try {
//     const res = await Taro.request({
//       url: '/city',
//       method: 'GET'
//     })
//     // 这里处理城市数据，根据实际API返回结构调整
//     console.log('城市数据:', res.data)
//   } catch (error) {
//     console.error('获取城市数据失败:', error)
//   }
// }

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return

  loading.value = true

  try {
    http.post('/index.php/index/api/index', 
      {
        Func:"appoint",
        data:{
            name: form.name,
            telephone: form.phone,
            province: form.region[0],
            city: form.region[1],
            district: form.region[2],
            address: form.address,
            remark: form.remark,
            pic: form.images,
          }
    }).then(res => { 
      console.log('提交结果:', res)
      if(res.code == 0){
        Taro.showToast({
          title: '预约成功',
          icon: 'success',
          duration: 2000
        })
        // 清空表单
        form.name = ''
        form.phone = ''
        form.region = ['天津市', '市辖区', '南开区']
        form.address = ''
        form.remark = ''
        form.images = []
      } else {
        Taro.showToast({
          title: res.msg || '预约失败，请稍后再试',
          icon: 'none',
          duration: 2000
        })
      }
    })
    
   
  } catch (error) {
    // showToast.fail('网络错误，请重试')
  } finally {
    loading.value = false
  }
}

// 初始化时获取城市数据
// onMounted(() => {
//   getCityData()
// })
</script>

<style lang="scss">
/* 重置按钮默认样式 */
button {
  margin: 0;
  padding: 0;
  border: none;
  background: none;
  line-height: 1;
}

button::after {
  border: none;
}

/* 确保输入框在微信小程序中显示正确 */
input, picker {
  background-color: transparent;
  height: auto;
  min-height: auto;
  line-height: normal;
}

.taro-textarea {
  background-color: transparent;
}

/* 错误提示样式 */
.error-message {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 10rpx;
}
</style>